export default {
    namespaced: true,
    state: {
        loggedIn: false,
        userInfo: null,
        userType: null, // 1 学生 2 教师 3 管理员
        permissions: []
    },
    mutations: {
        updateloggedIn(state, userInfo = null) {
            state.loggedIn = true
            state.userInfo = userInfo
            // 解析并写入 userType（兼容不同字段命名、位掩码、用户名推断）
            const deriveUserType = () => {
                if (!userInfo) return null
                if (userInfo.userType) return userInfo.userType
                if (userInfo.type) return userInfo.type
                if (userInfo.role) return userInfo.role
                // 如果有 privilege / permission 且包含 admin 位 (1<<7)
                const privNumSource = (typeof userInfo.privilege !== 'undefined') ? userInfo.privilege : userInfo.permission
                if (typeof privNumSource !== 'undefined') {
                    const num = typeof privNumSource === 'number' ? privNumSource : (/^\d+$/.test(privNumSource) ? parseInt(privNumSource,10) : 0)
                    if ((num & (1 << 7)) !== 0) return 3
                    // 新增：如果存在任意后台权限位(0-6 任一位) 也视为管理员（普通管理员）
                    const lowerMask = (1<<7)-1 // 0b01111111
                    if ((num & lowerMask) !== 0) return 3
                }
                // 用户名为 admin 兜底视为管理员
                if ((userInfo.username || '').toLowerCase() === 'admin') return 3
                // 本地缓存回填（在 loginStatus 未返回 userType 时）
                try {
                    const cached = localStorage.getItem('userType')
                    if (cached) return parseInt(cached,10)
                } catch(e) {}
                return null
            }
            state.userType = deriveUserType()
            // 权限解析增强：支持多字段、多格式、同义词
            const parsePermissions = (user) => {
                if (!user) return []
                const synonymMap = {
                    dept: ['dept','department','系','系管理'],
                    major: ['major','专业','专业管理'],
                    class: ['class','班级','班级管理'],
                    student: ['student','学生','学生管理'],
                    teacher: ['teacher','教师','教师管理'],
                    course: ['course','课程','课程管理'],
                    selection: ['selection','courseSelection','选课','选课管理'],
                    admin: ['admin','管理员','管理员管理','root','super']
                }
                const normalizeToken = (t) => {
                    if (!t) return null
                    const token = String(t).trim().toLowerCase()
                    for (const std in synonymMap) {
                        if (synonymMap[std].some(s => s.toLowerCase() === token)) return std
                    }
                    return null
                }
                const collected = new Set()
                // 1. 直接支持位掩码 privilege / privilegeString
                const rawPriv = user.privilegeString || user.privilege || user.permission
                if (typeof rawPriv === 'number' || (/^\d+$/.test(rawPriv || ''))) {
                    const num = typeof rawPriv === 'number' ? rawPriv : parseInt(rawPriv, 10)
                    const bitMapping = { dept:1<<0, major:1<<1, class:1<<2, student:1<<3, teacher:1<<4, course:1<<5, selection:1<<6, admin:1<<7 }
                    Object.keys(bitMapping).forEach(k => { if ( (num & bitMapping[k]) !== 0) collected.add(k) })
                }
                // 2. 逗号分隔字符串（可能是 privilegeString 里已经是 key 列表）
                if (typeof rawPriv === 'string' && rawPriv.includes(',')) {
                    rawPriv.split(',').forEach(tok => { const n = normalizeToken(tok); if (n) collected.add(n) })
                }
                // 3. privilegeFields: 可能是数组（字符串/对象）
                const pf = user.privilegeFields || user.privileges || user.permissionList || user.permissions
                if (Array.isArray(pf)) {
                    pf.forEach(item => {
                        if (typeof item === 'string') { const n = normalizeToken(item); if (n) collected.add(n) }
                        else if (item && typeof item === 'object') {
                            const cand = item.code || item.key || item.name || item.id
                            const n = normalizeToken(cand)
                            if (n) collected.add(n)
                        }
                    })
                }
                return Array.from(collected)
            }
            if (userInfo) {
                const parsed = parsePermissions(userInfo)
                if (process.env.NODE_ENV !== 'production') {
                    try { console.log('[permission-debug] rawBits=', userInfo.privilege || userInfo.permission, 'parsed=', parsed) } catch(e) {}
                }
                state.permissions = parsed
                if (parsed.length === 0) {
                    // 输出一次调试日志，帮助排查后台返回结构
                    try { console.warn('[permission] 未解析出有效权限，userInfo=', JSON.parse(JSON.stringify(userInfo))) } catch(e) {}
                }
                // 兜底：如果尚未识别为管理员且已有后台权限位，则设置 userType=3
                if (state.userType !== 3 && parsed.length > 0) {
                    state.userType = 3
                }
            } else {
                state.permissions = []
            }
            try { localStorage.setItem('userInfo', JSON.stringify(userInfo || {})) } catch(e) { /* ignore */ }
        },
        logout(state) {
            state.loggedIn = false
            state.userInfo = null
            state.userType = null
            state.permissions = []
            try { localStorage.removeItem('userInfo') } catch(e) { /* ignore */ }
        }
    },
    getters: {
        hasPermission: (state) => (permission) => {
            return state.permissions.includes(permission)
        },
        hasAnyPermission: (state) => (arr=[]) => {
            return arr.some(p => state.permissions.includes(p))
        },
        // 超级管理员判定：管理员身份 + (用户名为 admin 或 拥有 admin 权限位)
        isSuperAdmin: (state) => {
            if (state.userType !== 3) return false
            const username = (state.userInfo?.username || '').toLowerCase()
            if (username === 'admin') return true
            return state.permissions.includes('admin')
        },
        canAccess: (state) => (route) => {
            const routePermissionMap = {
                '/department': 'dept',
                '/major': 'major', 
                '/class': 'class',
                '/student': 'student',
                '/teacher': 'teacher',
                '/course': 'course',
                '/course-selection': 'selection',
                '/admin': 'admin'
            }
            const requiredPermission = routePermissionMap[route]
            return !requiredPermission || state.permissions.includes(requiredPermission)
        }
    }
}